import React, { useRef } from 'react';
import { Form } from 'antd';
import BasicArea from './Area/BasicArea';
import ResourceArea from './Area/ResourceArea';
import DeviceArea from './Area/DeviceArea';
import ManagerArea from './Area/ManagerArea';
import ReplyArea from './Area/ReplyArea';
import FooterArea from './Area/FooterArea';

/**
 * 验收表单
 */
function AcceptanceForm(props) {
    const { edit, initialValues, submitting, onSubmit } = props;

    const managerName = 'customerResponse';
    const managersRef = useRef([]);
    const managerValues = (managers) => {
        const assign = managers.length !== managersRef.current.length;
        return { appointStr: assign ? '指定' : '未指定', [managerName]: assign ? managers : [] };
    };

    const [form] = Form.useForm();
    const { validateFields } = form;

    return (
        <Form form={form} initialValues={initialValues}>
            <BasicArea edit={edit} initialValues={initialValues} />
            <ResourceArea />
            <DeviceArea edit={edit} initialValues={initialValues} />
            {edit ? (
                <ReplyArea />
            ) : (
                <ManagerArea name={managerName} onSuccess={(data) => (managersRef.current = data)} />
            )}
            <FooterArea
                edit={edit}
                submitting={submitting}
                onSubmit={async (draft) => {
                    try {
                        const { [managerName]: managers, ...restFieldsValue } = await validateFields();

                        onSubmit({
                            ...restFieldsValue,
                            ...(edit ? undefined : managerValues(managers)),
                            isDraft: edit ? draft : undefined,
                            acceptanceMaterialId: edit ? initialValues.acceptanceMaterialId : undefined,
                        });
                    } catch (err) {
                        console.log(err);
                        // ...
                    }
                }}
            />
        </Form>
    );
}

export default AcceptanceForm;
